package com.clei.utils.mybatis;

import com.clei.annotation.SensitiveEntity;
import com.clei.annotation.SensitiveField;
import com.clei.utils.CollectionUtil;
import com.clei.utils.PrintUtil;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;

import java.lang.reflect.Field;
import java.sql.Statement;
import java.util.List;

/**
 * 解密拦截器
 *
 * @author Y
 * @date 2023-09-17
 */

@Intercepts({@Signature(type = ResultSetHandler.class, method = "handleResultSets", args = Statement.class)})
public class DecryptInterceptor implements Interceptor {

    private final DataEncryptor dataEncryptor = new AESDataEncryptor();

    /**
     * 拦截
     *
     * @param invocation invocation
     * @return Object
     * @throws Throwable Throwable
     */
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object resObj = null;
        try {
            // 获取结果
            resObj = invocation.proceed();
            if (null == resObj) {
                return null;
            }
            boolean isList = resObj instanceof List;
            Class<?> resClass = null;
            if (isList) {
                List resList = (List) resObj;
                if (CollectionUtil.isEmpty(resList)) {
                    return resObj;
                }
                resClass = resList.get(0).getClass();
            } else {
                resClass = resObj.getClass();
            }
            // 是否有SensitiveEntity注解
            boolean annotationPresent = resClass.isAnnotationPresent(SensitiveEntity.class);
            if (!annotationPresent) {
                return resObj;
            }

            Field[] fields = resClass.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                if (field.isAnnotationPresent(SensitiveField.class)) {
                    if (isList) {
                        List resList = (List) resObj;
                        for (Object o : resList) {
                            decrypt(o, field);
                        }
                    } else {
                        decrypt(resObj, field);
                    }
                }
            }
        } catch (Exception e) {
            PrintUtil.log("DecryptInterceptor intercept error ", e);
        }
        return resObj;
    }

    /**
     * 加密
     *
     * @param obj Object
     * @param f   Field
     * @return origin value
     */
    private void decrypt(Object obj, Field f) throws Exception {
        Object value = f.get(obj);
        // instanceof value为null会返回false
        if (!(value instanceof String)) {
            return;
        }

        String origin = dataEncryptor.decrypt(String.valueOf(value));
        f.set(obj, origin);
    }
}
